package com.lingjtx.common.core.algorithm;

import com.lingjtx.common.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtil {

    private static final Logger log = LoggerFactory.getLogger(AESUtil.class);

    public static String encrypt(String plainText, String key) {
        if (StringUtil.isEmpty(plainText) || StringUtil.isEmpty(key)) return null;
        // 创建AES加密算法实例(根据传入指定的秘钥进行加密)
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");

            // 初始化为加密模式，并将密钥注入到算法中
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);

            // 将传入的文本加密
            byte[] encrypted = cipher.doFinal(plainText.getBytes());

            //生成密文
            // 将密文进行Base64编码，方便传输
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            log.error("AESUtil encrypt异常：{}", e.getMessage());
            return null;
        }
    }

    public static String decrypt(String data, String key) {
        if (StringUtil.isEmpty(data) || StringUtil.isEmpty(key)) return null;
        try {
            // 创建AES解密算法实例
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");

            // 初始化为解密模式，并将密钥注入到算法中
            cipher.init(Cipher.DECRYPT_MODE, keySpec);

            // 将Base64编码的密文解码
            byte[] encrypted = Base64.getDecoder().decode(data);

            // 解密
            byte[] decrypted = cipher.doFinal(encrypted);
            return new String(decrypted);
        } catch (Exception e) {
            log.error("AESUtil decrypt异常：{}", e.getMessage());
            return null;
        }
    }

    public static String decryptToString(String ciphertext, String aesKey, String associatedData, String nonce) {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), "AES");
            GCMParameterSpec spec = new GCMParameterSpec(128, nonce.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            if (StringUtil.isNotEmpty(associatedData)) {
                cipher.updateAAD(associatedData.getBytes());
            }
            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("AES decryptToString 异常: {}", e.getMessage());
            return null;
        }
    }
}
